<!DOCTYPE html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Favicon icon-->

  <!-- Libs CSS -->
  <link href="{{ url_for('static', filename='css/bootstrap-icons.css') }}" rel="stylesheet">
  <link href="{{ url_for('static', filename='css/dropzone.css') }}" rel="stylesheet">
  <link href="{{ url_for('static', filename='css/materialdesignicons.min.css') }}" rel="stylesheet">
  <link href="{{ url_for('static', filename='css/prism-okaidia.css') }}" rel="stylesheet">
  <link href="{{ url_for('static', filename='css/modal.css') }}" rel="stylesheet">

  <!-- Theme CSS -->
  <link rel="stylesheet" href="{{ url_for('static', filename='css/theme.min.css') }}">
  <title>Homepage | Dash Ui - Bootstrap 5 Admin Dashboard Template</title>
</head>

<body class="bg-light">

  <div id="db-wrapper">
    <!-- navbar vertical -->
    <!-- Sidebar -->
    <nav class="navbar-vertical navbar">
      <div class="nav-scroller">
        <!-- Brand logo -->
        <a class="navbar-brand" href="">
          <img src="{{ url_for('static', filename='image/logo.png') }}" alt="Logo">
        </a>
        <!-- Navbar nav -->
        <ul class="navbar-nav flex-column" id="sideNavbar">
          <li class="nav-item">
            <a class="nav-link has-arrow active" href="{{ url_for('teacher.get_teacher') }}">
              <i data-feather="home" class="nav-icon icon-xs me-2"></i> Dashboar
            </a>
          </li>
          <!-- Nav item -->
          <li class="nav-item">
            <div class="navbar-heading">Layouts & Pages</div>
          </li>
          <!-- Nav item -->
          <li class="nav-item">
            <a class="nav-link has-arrow collapsed" href="#!" data-bs-toggle="collapse" data-bs-target="#navPages"
              aria-expanded="false" aria-controls="navPages">
              <i data-feather="layers" class="nav-icon icon-xs me-2"></i> Pages
            </a>
            <div id="navPages" class="collapse" data-bs-parent="#sideNavbar">
              <ul class="nav flex-column">
                <li class="nav-item">
                  <a class="nav-link" href="{{url_for('course.get_course_management')}}">
                    Course Management
                  </a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="{{url_for('student.get_student')}}">
                    Discussion
                  </a>
                </li>
              </ul>
            </div>
          </li>
        </ul>
      </div>
    </nav>
    <!-- Page content -->
    <div id="page-content">
      <div class="header @@classList">
        <!-- navbar -->
        <nav class="navbar-classic navbar navbar-expand-lg">
          <a id="nav-toggle" href="#"><i data-feather="menu" class="nav-icon me-2 icon-xs"></i></a>
          <div class="ms-lg-3 d-none d-md-none d-lg-block">
            <!-- Form -->
            <form class="d-flex align-items-center" method="post">
              <input type="search" class="form-control" placeholder="Search" name="title" id="title"
                value="{{ title }}">
              <button type="submit" class="btn btn-primary">Search</button>
            </form>
          </div>
          <!--Navbar nav -->
          <ul class="navbar-nav navbar-right-wrap ms-auto d-flex nav-top-wrap">
            <li class="dropdown stopevent">
              <a class="btn btn-light btn-icon rounded-circle indicator indicator-primary text-muted" href="#"
                role="button" id="dropdownNotification" data-bs-toggle="dropdown" aria-haspopup="true"
                aria-expanded="false">
                <i class="icon-xs" data-feather="bell"></i>
              </a>
              <div class="dropdown-menu dropdown-menu-lg dropdown-menu-end" aria-labelledby="dropdownNotification">
                <div>
                  <div class="border-bottom px-3 pt-2 pb-3 d-flex justify-content-between align-items-center">
                    <p class="mb-0 text-dark fw-medium fs-4">Notifications</p>
                    <a href="#" class="text-muted">
                      <span><i class="me-1 icon-xxs" data-feather="settings"></i></span>
                    </a>
                  </div>
                  <!-- List group -->
                  <ul class="list-group list-group-flush notification-list-scroll">
                    <!-- List group item -->
                    <li class="list-group-item bg-light">
                      <a href="#" class="text-muted">
                        <h5 class=" mb-1">Rishi Chopra</h5>
                        <p class="mb-0">Mauris blandit erat id nunc blandit, ac eleifend dolor pretium。</p>
                      </a>
                    </li>
                    <!-- List group item -->
                    <li class="list-group-item">
                      <a href="#" class="text-muted">
                        <h5 class=" mb-1">Neha Kannned</h5>
                        <p class="mb-0">Proin at elit vel est condimentum elementum id in ante. Maecenas et sapien
                          metus。</p>
                      </a>
                    </li>
                    <!-- List group item -->
                    <li class="list-group-item">
                      <a href="#" class="text-muted">
                        <h5 class=" mb-1">Nirmala Chauhan</h5>
                        <p class="mb-0">Morbi maximus urna lobortis elit sollicitudin sollicitudieget elit vel pretium。
                        </p>
                      </a>
                    </li>
                    <!-- List group item -->
                    <li class="list-group-item">
                      <a href="#" class="text-muted">
                        <h5 class=" mb-1">Sina Ray</h5>
                        <p class="mb-0">Sed aliquam augue sit amet mauris volutpat hendrerit sed nunc eu diam。</p>
                      </a>
                    </li>
                  </ul>
                  <div class="border-top px-3 py-2 text-center">
                    <a href="#" class="text-inherit fw-semi-bold">View all Notifications</a>
                  </div>
                </div>
              </div>
            </li>
            <!-- List -->
            <li class="dropdown ms-2">
              <a class="rounded-circle" href="#" role="button" id="dropdownUser" data-bs-toggle="dropdown"
                aria-haspopup="true" aria-expanded="false">
                <div class="avatar avatar-md avatar-indicators avatar-online">
                  <img alt="avatar" src="{{ url_for('static', filename='picture/avatar-1.jpg') }}"
                    class="rounded-circle">
                </div>
              </a>
              <div class="dropdown-menu dropdown-menu-end" aria-labelledby="dropdownUser">
                <div class="px-4 pb-0 pt-2">
                  <div class="lh-1 ">
                    <h5 class="mb-1">{{ name }}</h5>
                  </div>
                  <div class=" dropdown-divider mt-3 mb-2"></div>
                </div>
                <ul class="list-unstyled">
                  <li>
                    <a class="dropdown-item" href="#">
                      <i class="me-2 icon-xxs dropdown-item-icon" data-feather="settings"></i>Account Settings
                    </a>
                  </li>
                  <li>
                    <a class="dropdown-item" href="{{ url_for('user.logout') }}">
                      <i class="me-2 icon-xxs dropdown-item-icon" data-feather="power"></i>Sign Out
                    </a>
                  </li>
                </ul>
              </div>
            </li>
          </ul>
        </nav>
      </div>
      <!-- Container fluid -->
      <div class="bg-primary pt-10 pb-21"></div>
      <div class="container-fluid mt-n22 px-6">
        <div class="row mt-6">
          <div class="col-md-12 col-12">
            <div class="card" id="mainCard">
              <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-3">
                  <h4 id="headerTitle">User Management</h4>
                  <button id="backButton" class="btn btn-secondary" style="display: none;">Back</button>
                </div>
                <div id="importSection" class="mb-3">
                  <input type="file" id="importFile" class="form-control">
                  <button id="importButton" class="btn btn-primary mt-2">Import Students</button>
                </div>
                <div id="createSection" class="mb-3 d-flex">
                  <input type="number" id="newStudentId" class="form-control me-2" placeholder="Enter student ID">
                  <input type="text" id="newStudentName" class="form-control me-2" placeholder="Enter student name">
                  <input type="email" id="newStudentEmail" class="form-control me-2" placeholder="Enter student email">
                  <button id="createStudentButton" class="btn btn-primary">Create Student</button>
                </div>
                <div class="list-group" id="studentList">
                  <!-- Student entries will be added here via JavaScript -->
                </div>
              </div>
            </div>
            <div class="card" id="progressCard" style="display: none;">
              <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-3">
                  <h4 id="progressHeaderTitle"></h4>
                  <button id="progressBackButton" class="btn btn-secondary">Back</button>
                </div>
                <div id="progressContent">
                  <!-- Progress content will be added here via JavaScript -->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
    <!-- row  -->

  </div>

  <!-- Scripts -->
  <!-- Libs JS -->
  <script src="{{ url_for('static', filename='js/jquery.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/bootstrap.bundle.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/jquery.slimscroll.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/feather.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/prism.js') }}"></script>
  <script src="{{ url_for('static', filename='js/apexcharts.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/dropzone.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/prism-toolbar.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/prism-copy-to-clipboard.min.js') }}"></script>
  <script src="{{ url_for('static', filename='js/modal.js') }}"></script>
  <script>
    $(document).ready(function () {
      let students = [];

      const $studentList = $('#studentList');
      const $headerTitle = $('#headerTitle');
      const $backButton = $('#backButton');
      const $importSection = $('#importSection');
      const $createSection = $('#createSection');
      const $mainCard = $('#mainCard');
      const $progressCard = $('#progressCard');
      const $progressHeaderTitle = $('#progressHeaderTitle');
      const $progressBackButton = $('#progressBackButton');
      const $progressContent = $('#progressContent');
      const $importFile = $('#importFile');
      const $newStudentId = $('#newStudentId');
      const $newStudentName = $('#newStudentName');
      const $newStudentEmail = $('#newStudentEmail');
      const $createStudentButton = $('#createStudentButton');
      const $importStudentButton = $('#importButton');

      $importStudentButton.click(function () {
        $importFile.click();
      });

      let editingStudentId = null; // 当前正在编辑的学生ID

      const http = 'http://172.16.10.35:5001';
      const loadStudents = () => {
        $studentList.empty(); // 清空当前内容
        students.forEach(student => {
          const $studentItem = $('<div>')
            .addClass('list-group-item d-flex justify-content-between align-items-center');

          // 判断当前学生是否正在编辑
          if (editingStudentId === student.user_id) {
            $studentItem.html(`
          <span class="student-info" data-id="${student.user_id}">${student.user_id}</span>
          <div class="d-flex align-items-center justify-content-start">
            <input type="text" class="form-control me-2" value="${student.user_name}" />
            <input type="email" class="form-control me-2" value="${student.email}" />
            <div class="d-flex">
              <button class="btn btn-sm btn-success ms-2 save-btn">Save</button>
              <button class="btn btn-sm btn-secondary ms-2 cancel-btn">Cancel</button>
            </div>
          </div>
        `);
          } else {
            $studentItem.html(`
          <span class="student-info" data-id="${student.user_id}">${student.user_name} (${student.email})</span>
          <div>
            <button class="btn btn-sm btn-info me-2 edit-btn">Edit</button>
            <button class="btn btn-sm btn-warning me-2 progress-btn" data-id="${student.user_id}">Progress</button>
            <button class="btn btn-sm btn-danger delete-btn" data-id="${student.user_id}">Delete</button>
          </div>
        `);
          }
          $studentList.append($studentItem);
        });

        // 处理编辑按钮点击事件
        $('.edit-btn').off('click').on('click', function (event) {
          editingStudentId = parseInt($(this).closest('.list-group-item').find('.student-info').data('id'));
          loadStudents(); // 重新加载学生列表
        });

        // 处理保存和取消按钮事件
        $('.save-btn').off('click').on('click', function (event) {
          const $studentItem = $(this).closest('.list-group-item');
          const name = $studentItem.find('input[type="text"]').val();
          const email = $studentItem.find('input[type="email"]').val();

          // 更新学生信息
          let student = students.find(s => s.user_id === editingStudentId);

          student.user_name = name;
          student.email = email;

          editingStudentId = null; // 清空编辑状态

          // 调用接口更新学生信息
          $.ajax({
            type: 'POST',
            url: `${http}/edit_student/${student.user_id}`, // 使用学生ID拼接接口路径
            data: JSON.stringify({ name: student.user_name, email: student.email }),
            contentType: 'application/json',
            success: function (response) {
              editingStudentId = null; // 清空编辑状态
              loadStudents(); // 重新加载学生列表
            },
            error: function (xhr, status, error) {
              alert('Failed to update student: ' + error);
            }
          });

        });

        $('.cancel-btn').off('click').on('click', function () {
          editingStudentId = null; // 清空编辑状态
          loadStudents(); // 重新加载学生列表
        });

        $('.progress-btn').off('click').on('click', function (event) {
          const studentId = $(this).data('id');
          const student = students.find(s => s.user_id === parseInt(studentId));
          showProgress(student);
        });

        // 新增删除功能
        $studentList.off('click', '.delete-btn').on('click', '.delete-btn', function (event) {
          const studentId = $(this).data('id');
          const studentName = students.find(s => s.user_id === parseInt(studentId)).user_name; // 获取学生姓名

          confirmDialog(`Are you sure you want to delete ${studentName}?`, () => {
            // 删除学生逻辑
            students = students.filter(s => s.user_id !== parseInt(studentId));

            $.ajax({
              type: 'POST',
              url: `${http}/delete_student/${studentId}`, // 使用学生ID拼接接口路径
              success: function (response) {
                if (response.code == 0 || response.code == 200) {
                  editingStudentId = null; // 清空编辑状态
                  loadStudents(); // 重新加载学生列表
                }
              },
              error: function (xhr, status, error) {
                alert('Failed to delete student: ' + error);
              }
            });
          });
        });
      };

      const showProgress = (student) => {
        $mainCard.hide();
        $progressCard.show();
        $progressHeaderTitle.text(`${student.user_name}'s Progress`);

        let videoProgressHtml = '<ul>';
        student.videoProgress.forEach(progress => {
          videoProgressHtml += `<li>${progress.video}: ${progress.time}</li>`;
        });
        videoProgressHtml += '</ul>';

        $progressContent.html(`
      <p>Email: ${student.email}</p>
      <p>Overall Progress: ${student.progress}%</p>
      <h5>Video Progress:</h5>
      ${videoProgressHtml}
    `);
      };

      $progressBackButton.click(function () {
        $mainCard.show();
        $progressCard.hide();
      });

      $importFile.change(function (event) {
        const file = this.files[0];
        // 读取文件逻辑可以使用 FileReader
      });

      $.ajax({
        type: 'get',
        url: `${http}/student_list`, // 替换为实际的接口路径
        success: function (response) {
          if (response.code == 0 || response.code == 200) {
            students = response.data;
            $newStudentId.val('');
            $newStudentName.val('');
            $newStudentEmail.val('');
            loadStudents();
          }
        },
        error: function (xhr, status, error) {
          alert('Failed to fetch student list: ' + error);
        }
      });

      $createStudentButton.click(function () {
        const id = parseInt($newStudentId.val().trim(), 10);
        const name = $newStudentName.val().trim();
        const email = $newStudentEmail.val().trim();
        if (!isNaN(id) && name && email) {
          let data = { user_id: id, user_name: name, email: email };
          $.ajax({
            type: 'POST',
            url: `${http}/add_student`, // 替换为实际的接口路径
            data: JSON.stringify(data),
            contentType: 'application/json',
            success: function (response) {
              if (response.code == 0 || response.code == 200) {
                students.push(data);
                loadStudents();
              }
            },
            error: function (xhr, status, error) {
              alert('Failed to create student: ' + error);
            }
          });
        }
      });
    });

  </script>

  <!-- Theme JS -->
  <script src="{{ url_for('static', filename='js/theme.min.js') }}"></script>

</body>

</html>